from django.shortcuts import render,redirect
from django.http import HttpResponse
from myadmin.models import User
from django.urls import reverse


from PIL import  Image, ImageDraw, ImageFont

import random

import io


# Create your views here.

def index(request):
    # 通过render方法让html模板喧染页面
    return render(request,"myadmin/index/index.html")

def login(request):
    # 通过render方法让html模板喧染页面
    return render(request,"myadmin/index/login.html")

def dologin(request):
    username = request.POST['username']
    userpwd = request.POST['userpwd']
    code = request.POST['verifycode']

    try:
        # 执行验证码操作
        if code != request.session['verifycode']:
            context = {"info": "验证码错误！！"}
            return render(request, "myadmin/index/login.html", context)

        user = User.objects.get(username=username)


        if user.status == 1:
            if user.userpwd == userpwd:
                # session中不支持存入对象，需要放入字符串或字典
                request.session['adminuser'] = user.toDict()
                # 重定向到后台管理首页
                return redirect(reverse('myadmin_index'))
            else:
                context = {"info": "用户密码不正确！！"}
        else:
            context = {"info": "用户账号无效！！"}
        # 判断是否为后台有效用户
    except Exception as err:
        print(err)
        context = {"info":"登录账号不存在"}

    return render(request, "myadmin/index/login.html", context)

def logout(request):
    del request.session['adminuser']
    return redirect(reverse('myadmin_login'))

# 验证码输出
def verifycode(request):
    # 引入绘图模块和随机函数
    from PIL import  Image, ImageDraw, ImageFont
    import random
    # 定义变量，用于画现的背景色，高和宽
    bgcolor = (random.randrange(20,100),random.randrange(20,100),255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB',(width,height),bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point函数绘制噪点
    for i in range(0,100):
        xy = (random.randrange(0,width),random.randrange(0,height))
        fill = (random.randrange(0,255),255,random.randrange(0,255))
        draw.point(xy,fill=fill)
    #定义验证码的备选值
    str1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    # 随机选4个值作为验证码
    rand_str = ''
    for i in range(0,4):
        rand_str += str1[random.randrange(0,len(str1))]
    #
    # 构造字体颜色和
    font = ImageFont.truetype('static/impact.ttf',23)
    # font = ImageFont.load_default().font  默认字有可能不好使用，可以使用windows系统中的
    # c:/windows/font下的字体复制至项目/static/下即可
    fontcolor = (255,random.randrange(0,255),random.randrange(0,255))

    # 绘制4个字
    draw.text((5,2),rand_str[0],font=font,fill=fontcolor)
    draw.text((25,2),rand_str[1],font=font,fill=fontcolor)
    draw.text((50,2),rand_str[2],font=font,fill=fontcolor)
    draw.text((75,2),rand_str[3],font=font,fill=fontcolor)

    #释放画笔
    del draw
    #存入session，用于验证，需要开启Django的session
    request.session['verifycode'] = rand_str

    # 内存文件操作
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型 为png
    im.save(buf,'png')

    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(),'image/png')